<template>
  <div class="process-main">
    <div class="add_btn_top">
      <el-button class="button primary-button" size="mini" @click="handAdd"
        ><i class="el-icon-plus"></i>添加
      </el-button>
      <!-- <el-button class="button" size="mini" @click="handleImport">
        <svg-icon class="svg-icon" icon-class="import" />导入
      </el-button>
      <el-button class="button" size="mini" @click="handleExport">
        <svg-icon class="svg-icon" icon-class="import" />导出
      </el-button>
      <el-button class="button" size="mini">
        <svg-icon class="svg-icon" icon-class="import" />第三方系统集成
      </el-button> -->
      <el-button
        icon="el-icon-arrow-down"
        type="primary"
        size="mini"
        @click="handleAddSubmit"
        >发送</el-button
      >
      <div style="margin: 0 10px" :style="{ color: switchTextColor }">
        {{ switchText }}
      </div>
      <el-switch class="screenSwitch" active-color="#2680D2" v-model="screen">
      </el-switch>
    </div>
    <el-container>
      <el-main style="padding: 0; background: #fff;">
        <div style="width:100%;" class="flex-x flex-center">
          <el-tabs v-model="activeName" @tab-click="handleClick" stretch>
            <el-tab-pane
              v-for="item in manufactureSiteList"
              :key="item.name"
              :label="item.name"
              :name="item.name"
            ></el-tab-pane>
          </el-tabs>
        </div>
        <el-table
          size="small"
          ref="multipleTable"
          border
          :data="productionData"
          height="100px"
          v-adaptive
          style="width: 100%"
          row-key="id"
          :row-class-name="tableRowClassName"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            :reserve-selection="true"
            :selectable="selectable"
            align="center"
            type="selection"
          >
          </el-table-column>
          <el-table-column align="center" type="index" width="55" label="序号">
          </el-table-column>

          <template v-for="(item, index) in getColumnList">
            <template>
              <el-table-column
                v-if="item.type === 'formula'"
                :key="index"
                :show-overflow-tooltip="true"
                :width="item.width"
                :prop="item.prop"
                :label="item.label"
                align="center"
                :type="item.type"
              >
                <template slot-scope="props">
                  <el-popover placement="bottom" width="800" trigger="click">
                    <div style="width: 100%">
                      <el-table
                        v-if="
                          props.row.formula &&
                            props.row.formula.formulaParameter.length
                        "
                        max-height="500px"
                        min-height="100%"
                        border
                        size="mini"
                        :data="props.row.formula.formulaParameter"
                        style="width: 100%"
                      >
                        <el-table-column
                          v-for="(item, index) in props.row.formula
                            .formulaParameter[0].keys"
                          :label="item"
                          :key="index"
                          align="center"
                        >
                          <template slot-scope="scope">
                            {{ scope.row.values[index] }}
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                    <el-button slot="reference" type="text">查看工艺</el-button>
                  </el-popover>
                </template>
              </el-table-column>
              <el-table-column
                sortable
                :show-overflow-tooltip="true"
                :key="index"
                v-if="isTabShow(item.label) && item.type !== 'formula'"
                :min-width="item.width"
                :prop="item.prop"
                :label="item.label"
                align="center"
                :type="item.type"
              >
                <template slot-scope="scope">
                  <span
                    v-if="
                      item.prop === 'token' &&
                        scope.row.token !==
                          '00000000-0000-0000-0000-000000000000'
                    "
                    @click="checkDetails(scope.row.token)"
                    style="color: #409eff; cursor: pointer"
                    >{{ scope.row.token }}</span
                  >
                  <span v-if="item.prop === 'startTime'">
                    {{ scope.row.startTime | formatDate }}
                  </span>
                  <span
                    v-if="item.prop !== 'token' && item.prop !== 'startTime'"
                    >{{ scope.row[item.prop] }}</span
                  >
                </template>
              </el-table-column>
            </template>
          </template>
          <el-table-column
            prop="createdDate"
            label="创建时间"
            align="center"
            width="180"
          >
            <template slot-scope="scope">
              {{ scope.row.createdDate | formatDate }}
            </template>
          </el-table-column>
          <el-table-column
            prop="updatedDate"
            label="更新时间"
            width="180"
            align="center"
          >
            <template slot-scope="scope">
              {{ scope.row.updatedDate | formatDate }}
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="120px"
            align="center"
          >
            <!-- eslint-disable-next-line -->
            <template slot="header" slot-scope="scope">
              <div class="flex-x flex-space" style="padding: 0 10px">
                <div>操作</div>
                <el-popover width="100" trigger="click">
                  <div class="column_search_box">
                    <div class="column_title">自定义表头字段</div>
                    <el-checkbox-group v-model="colCheckList">
                      <div class="flex-y column_search">
                        <el-checkbox
                          :label="item.label"
                          v-for="item in getColumnCheckList"
                          :key="item.label"
                        >
                          {{ item.label }}</el-checkbox
                        >
                      </div>
                    </el-checkbox-group>
                  </div>
                  <span slot="reference" class="el-icon-s-grid"></span>
                </el-popover>
              </div>
            </template>
            <template slot-scope="scope">
              <el-button
                type="text"
                size="mini"
                icon="el-icon-edit-outline"
                @click="handEdit(scope.row.token)"
              ></el-button>
              <el-button
                type="text"
                size="mini"
                icon="el-icon-delete"
                @click="handDelete(scope.row.token)"
              ></el-button>
              <!-- <el-button
                type="text"
                size="mini"
                icon="el-icon-view"
                @click="checkDetails(scope.row.token)"
              ></el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          @pagination="pagination"
          :total="total"
          :page="pageNum"
          :limit="pageSize"
          :pageSizes="pageSizes"
        />
      </el-main>
      <el-aside
        style="background: #fff; padding: 10px; margin-left: 10px"
        width="18%"
        v-show="screen"
      >
        <Search
          :dataAll="productionDataAll"
          @setFilterList="setFilterList"
        ></Search>
      </el-aside>
    </el-container>

    <AddDialog
      :addFlag="addFlag"
      :isedit="isedit"
      :title="title"
      :token="productionTaskToken"
      @closeDialog="closeDialog"
      ref="addDialogRef"
      :manufactureSite="activeName"
      :reportId="reportId"
      :templateId="templateId"
    ></AddDialog>
    <RuleDialog
      ref="ruleDialogRefs"
      :showDialog.sync="ruleShowDialog"
      :rulesOptions="rulesOptions"
      @submitForm="submitForm"
    ></RuleDialog>
    <DetailsDialog
      :token="productionTaskToken"
      :showDialog.sync="showDetailsDialog"
    ></DetailsDialog>
    <MaterialDialog
      :token="materialToken"
      :showDialog.sync="materialShowDialog"
    ></MaterialDialog>
    <!-- 导入 -->
    <ImportDialog
      @closeDialog="closeImportDialog"
      :showDialog.sync="showImportDialog"
    ></ImportDialog>
    <!-- 导出 -->
    <ExportDialog
      :showDialog.sync="showExportDialog"
      :tableData="productionDataAll"
      :userList="userList"
    ></ExportDialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import Pagination from "@/views/common/page";
import AddDialog from "./AddDialog.vue";
import { getTasks, delTasks, submitTask } from "@/api/productionTaskAccount";
import Search from "./searchFilter.vue";
import { TENANT_TITLE } from "@/utils/local";
import RuleDialog from "./RuleDialog.vue";
import { getRules } from "@/api/productionRule";
import DetailsDialog from "./DetailsDialog.vue";
import { currentDate } from "@/utils/currentDate";
import MaterialDialog from "../materialAccount/components/DetailsDialog.vue";
import ImportDialog from "./ImportDialog.vue";
import ExportDialog from "./ExportDialog.vue";
import { getUserList } from "@/api/userAuth";
import { getTemplate } from "@/api/technology";
const COLUMN_LIST = [
  {
    label: "工艺信息",
    prop: "",
    type: "formula",
    width: "150px",
    hideCheck: true // 不进行筛选
  },
  {
    label: "任务号",
    prop: "token",
    width: "150px"
  },
  {
    label: "来件单位",
    prop: "unit",
    hideCheck: true,
    width: "150px"
  },

  // {
  //   label: "制造单元",
  //   prop: "manufactureSite",
  //   width: "150px",
  // },
  {
    label: "批次号",
    prop: "batchNumber",
    width: "150px"
  },
  {
    label: "零件号",
    width: "150px",
    prop: "partNumber"
  },
  {
    label: "零件名称",
    prop: "partName",
    width: "150px"
  },
  {
    label: "委托工序号",
    width: "150px",
    prop: "entrustProcessNumber"
  },
  {
    label: "委托工序名称",
    width: "150px",
    prop: "entrustProcessName"
  },
  {
    label: "工序/工步号",
    width: "150px",
    prop: "processNumber"
  },
  {
    label: "工序/工步名称",
    width: "150px",
    prop: "processName"
  },
  {
    label: "材料牌号",
    width: "150px",
    prop: "materialMark"
  },
  {
    label: "来件数量",
    prop: "partTotalCount",
    width: "150px"
  },
  {
    label: "状态",
    prop: "state",
    width: "150px"
  },
  //new
  // {
  //   label: "物料台账ID",
  //   prop: "materialAccountId",
  //   width: "150px"
  // },
  {
    label: "型别",
    prop: "model",
    width: "150px"
  },

  // {
  //   label: "工艺配方ID",
  //   prop: "formulaId",
  //   width: "150px"
  // },
  {
    label: "工艺版次",
    prop: "version",
    width: "150px"
  },
  {
    label: "工序版次",
    prop: "processVersion",
    width: "150px"
  }
];
export default {
  components: {
    ExportDialog,
    ImportDialog,
    Pagination,
    AddDialog,
    Search,
    RuleDialog,
    DetailsDialog,
    MaterialDialog
  },

  data() {
    return {
      activeName: "",
      activeToken: "",
      showExportDialog: false,
      showImportDialog: false,
      ruleShowDialog: false,
      rulesOptions: [],
      screen: false,
      switchTextColor: "#666666",
      switchText: "显示筛选",
      title: "生产任务",
      pageNum: 1,
      pageSize: 20,

      pageSizes: [20, 50, 100, 300],
      total: 0,
      addFlag: false,
      isedit: false,
      productionTaskToken: "",
      editmetaData: {},
      editmetaData: true,
      productionData: [],
      multipleSelection: [],
      colCheckList: COLUMN_LIST.map(item => item.label),
      showDetailsDialog: false,
      materialToken: "",
      materialShowDialog: false,
      userList: [],
      productionDataAll: [],
      searchParams: {},
      reportId: "", //对应模板reportId
      templateId: "" //对应模板id
    };
  },
  computed: {
    ...mapGetters(["manufactureSiteList"]),
    getColumnCheckList() {
      return COLUMN_LIST.filter(item => !item.hideCheck);
    },
    getColumnList() {
      return COLUMN_LIST;
    },
    isTabShow() {
      return function(name) {
        return this.colCheckList.includes(name);
      };
    },
    isCasting() {
      const { name } = this.$store.getters.tenant;
      return name == TENANT_TITLE[2];
    }
  },
  mounted() {
    this.activeName = this.$route.query.activeName
      ? this.$route.query.activeName
      : this.manufactureSiteList[0].name;
    this.activeToken = this.manufactureSiteList.find(
      item => item.name == this.activeName
    ).token;
    getTemplate({
      page: 1,
      pageSize: 100,
      manufactureSite: this.activeName
    }).then(r => {
      const { data } = r;
      this.reportId =
        data.results && data.results.length ? data.results[0].token : "";
      this.templateId =
        data.results && data.results.length ? data.results[0].id : "";
    });
    getTasks({
      page: 1,
      includeFormula: true,
      pageSize: 0,
      manufactureSite: this.activeName
    }).then(res => {
      const r = res.data;
      this.productionDataAll = r.results;
    });
    getUserList().then(res => {
      const { data } = res.data;
      this.userList = data;
    });

    this.getRulesOptions();
    this.getproductionTaskData();
  },
  methods: {
    //table颜色
    tableRowClassName({ row }) {
      if (row.state === "就绪") {
        console.log("我进来了");
        return "";
      } else {
        return "row_color_3";
      }
    },
    handleClick(e) {
      this.activeToken = this.manufactureSiteList[e.index].token;
      console.log(this.activeToken);
      this.getproductionTaskData();
      getTemplate({
        page: 1,
        pageSize: 100,
        manufactureSite: this.activeName
      }).then(r => {
        const { data } = r;
        this.reportId =
          data.results && data.results.length ? data.results[0].token : "";
        this.templateId =
          data.results && data.results.length ? data.results[0].id : "";
        console.log(data.results);
      });
    },
    closeImportDialog(isRefresh) {
      if (isRefresh) {
        this.getproductionTaskData();
      }
    },
    // 导出
    handleExport() {
      this.showExportDialog = true;
    },
    // 导入
    handleImport() {
      this.showImportDialog = true;
    },
    checkMaterial(row) {
      this.materialToken = row.materialAccountId;
      this.materialShowDialog = true;
    },
    checkDetails(token) {
      this.showDetailsDialog = true;
      this.productionTaskToken = token;
    },
    selectable(row) {
      return row.state === "就绪";
    },
    getRulesOptions() {
      getRules({
        author: "",
        name: "",
        page: 1,
        pageSize: 0,
        state: "",
        token: "",
        version: ""
      }).then(res => {
        this.rulesOptions = res.data.results;
      });
    },
    async submitForm(ruleId) {
      const taskIdList = this.multipleSelection.map(item => item.id);
      try {
        const res = await submitTask({
          taskIdList,
          ruleId,
          submitType: "发送",
          metadata: {},
          token: ""
        });
        this.$refs.ruleDialogRefs.btnLoading = false;
        this.$refs.ruleDialogRefs.form.ruleId = "";
        this.ruleShowDialog = false;
        this.multipleSelection = [];
        this.$msg({
          type: "success",
          message: "发送成功"
        });
        // this.getproductionTaskData();
        this.$router.push({
          path: "/productionTask/furnaceTask/furnaceRecipeList",
          query: {
            activeName: this.activeName
          }
        });
      } catch (error) {
        this.$refs.ruleDialogRefs.btnLoading = false;
      }
    },
    async handleAddSubmit() {
      if (this.multipleSelection.length) {
        this.$confirm(
          `当前选中 ${this.multipleSelection.length} 个任务,是否确认发送至合炉任务管理?`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        )
          .then(() => {
            let flag = false;
            this.multipleSelection.forEach(row => {
              if (
                row.formula.deviceInfoList.length &&
                row.formula.deviceInfoList[0].deviceList.length
              ) {
              } else {
                flag = true;
              }
            });
            if (flag) {
              this.$msg({
                type: "warning",
                message: "当前任务工艺信息未绑定设备"
              });
            } else {
              if (this.rulesOptions && this.rulesOptions.length) {
                this.submitForm(this.rulesOptions[0].id);
              } else {
                this.$msg({
                  type: "warning",
                  message: "当前无合炉规则"
                });
              }
            }
            // this.ruleShowDialog = true;
          })
          .catch(err => {});
      } else {
        this.$msg("请选择物料收发台账");
      }
    },
    handleSelectionChange(rows) {
      console.log("rows :>> ", rows);
      this.multipleSelection = rows;
      // this.select_number = this.multipleSelection.length;
      // this.select_Id = [];
      // if (rows) {
      //   rows.forEach((row) => {
      //     if (row) {
      //       this.select_Id.push(row.id);
      //     }
      //   });
      // }
    },
    setFilterList(data) {
      if (data) {
        this.switchTextColor = "#2680D2";
        this.switchText = "显示筛选 ( 已筛选 )";
      } else {
        this.switchTextColor = "#666666";
        this.switchText = "显示筛选";
      }
      this.searchParams = data;
      // 筛选时 分页修改为第一页
      this.pageNum = 1;
      this.getproductionTaskData();
    },
    pagination({ page, limit }) {
      this.pageNum = page;
      this.pageSize = limit;
      this.getproductionTaskData();
    },
    indexMethod(index) {
      return index + 1;
    },
    //添加
    handAdd() {
      if (this.templateId) {
        this.isedit = false;
        this.addFlag = true;
      } else {
        this.$msg({
          type: "warning",
          message: "当前制造单元无工艺基础信息"
        });
      }
    },
    //编辑
    handEdit(token) {
      this.addFlag = true;
      this.isedit = true;
      this.productionTaskToken = token;
    },
    handDelete(token) {
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          delTasks(token).then(res => {
            this.$msg({
              type: "success",
              message: "操作成功!"
            });
            this.getproductionTaskData();
          });
        })
        .catch(c => {});
    },
    //获取生产任务列表
    getproductionTaskData() {
      console.log("this.searchParams :>> ", this.searchParams);
      var params = {
        manufactureSite: this.activeName,
        page: this.pageNum,
        includeFormula: true,
        pageSize: this.pageSize,
        ...this.searchParams,
        stateList:
          this.searchParams && this.searchParams.stateList
            ? this.searchParams.stateList
            : ["未就绪", "就绪"]
        // startDate: data && data.startDate ? data.startDate : currentDate(),
      };
      this.productionData = [];
      getTasks(params).then(res => {
        const r = res.data;
        this.total = r.numResults;
        this.productionData = r.results;
        this.multipleSelection = [];
        this.$nextTick(() => {
          this.$refs.multipleTable.clearSelection();
        });
      });
    },
    //关闭回调
    closeDialog(isRefresh) {
      // isRefresh是否刷新
      if (isRefresh) {
        this.getproductionTaskData();
      }
      this.addFlag = false;
    }
  }
};
</script>

<style>
/* @import "~@/assets/style/processCss/baseStyle.css"; */

.row_color_3 {
  background: #e4e7ed !important;
}
</style>
